<template>
  <div class="create_open_path_roam_box">
    <div class="inner_content_box">
      <div class="single_1_box_common">
        <div class="com_title_c"><img class="com_title_img" src="../../../assets/img/openlayer/1.png">路径信息获取</div>
        <div class="un_coding_c">（1）通过天地图服务获取路径信息：<a href="https://api.tianditu.gov.cn/v2/drive">https://api.tianditu.gov.cn/v2/drive</a>
        </div>
        <div class="un_coding_c">（2）通过高德地图服务获取路径信息：<a
            href="https://restapi.amap.com/v3/direction/driving">https://restapi.amap.com/v3/direction/driving</a></div>
        <div class="un_coding_c">（3）通过应急GIS（EGIS）获取路径信息</div>
        <div class="coding_1_box_common coding_row_1" style="height: 250px;">
          <pre><code class="language-javascript"
                     v-text="content"></code></pre>
        </div>
        <div class="un_coding_c">（4）通过其他地图服务获取数据</div>
      </div>

      <div class="single_1_box_common">
        <div class="com_title_c"><img class="com_title_img" src="../../../assets/img/openlayer/1.png">展示</div>
        <div class="map_content_box" id="map_content_1"></div>
        <div class="coding_1_box_common coding_row_1">
          <div class="un_coding_c">测试数据：</div>
          <pre><code class="language-javascript"
                     v-text="content1"></code></pre>
          <div class="un_coding_c">主要实现pathRoam.ts：</div>
          <pre><code class="language-javascript"
                     v-text="content2"></code></pre>
          <div class="un_coding_c">功能实现：</div>
          <pre><code class="language-javascript"
                     v-text="content3"></code></pre>
        </div>
      </div>

    </div>

  </div>
</template>

<script lang="ts" setup>
import Prism from 'prismjs';
import {nextTick, onMounted, ref} from "vue";

import pathPoint from '../data/pathPoint.json'
import 'ol/ol.css'
import {Map, View} from 'ol'
import {register} from 'ol/proj/proj4'
import {WebGLTile} from 'ol/layer'
import {Style} from 'ol/style'
import {ImageTile, XYZ} from 'ol/source'
import proj4 from 'proj4'
import pathRoam from "@/widgets/Openlayer@10_3_1/js/pathRoam";

const content = `
金安专网用户接口地址-申请：http://ip:port/oauth/token;
电子政务外网用户接口地址-调用：http://ip:port/service/api/egis/base/v1/wrps/driving;

金安专网用户接口地址-申请：http://ip:port/oauth/token;
电子政务外网用户接口地址-调用：http://ip:port/service/api/egis/base/v1/wrps/driving;

互联网接口地址-申请：http://ip:port/oauth/token;
互联网接口地址-调用：http://ip:port/service/api/egis/base/v1/wrps/driving;

`

const content1 = `
//这只是数据的一部分，格式就是这样
[
  [ 118.97950388611164, 34.55661723589262],
  [ 118.97958259739632,  34.55661000868944 ],
  [118.97989246323404,34.556549138809956 ],
  [ 118.97998911434216, 34.55647990646418 ],
  [  118.98006384669979, 34.55640474361138],
  [ 118.98015451643944, 34.55636650460343],
  [ 118.98025016544545, 34.556350233578186 ],
  [ 118.98044245448935, 34.556365650829285 ],
  [ 119.32854424410256, 34.476232730083865]
]

`
const content2 = `

import Feature from "ol/Feature";
import { Point, LineString } from "ol/geom";
import { Tile as TileLayer, Vector as VectorLayer } from "ol/layer";
import VectorSource from "ol/source/Vector";
import { Circle as CircleStyle, Fill, Icon, Stroke, Style, Text } from "ol/style";
import { getVectorContext } from "ol/render";
import { along, point, distance, lineString } from "@turf/turf";
import movePng from '../../../assets/img/openlayer/move.png'
import startPng from '../../../assets/img/openlayer/start.png'
import endPng from '../../../assets/img/openlayer/end.png'
let self:any=undefined;
/**
 * 模拟高德地图的路径样式
 * 暂时没用-留着当技术储备
 */
class PathNavigation{
    _map:any;
    progress:number;
    animating:boolean;
    speed:number;
    nowTime:any;
    textContent:string;
    routeCoords:Array<Array<number>>
    routeLength:number;
    route:any;
    routeFeature:any;
    geoMarker:any;
    startMarker:any;
    endMarker:any;
    styles:any;
    zoomScale:number;
    vectorLayer:any;
    center:Array<number>

    constructor () {
        this._map=undefined;
        this.progress=0;  //进度
        this.animating=false;//动画是否开始
        this.speed=0;// 速度
        // map: null,
        this.nowTime= null; // 当前时间
        this.textContent= "开始";
        this.routeCoords=[]; // 数组点集合
        this.routeLength=0; // 数组长度
        this.route=null; // 线-geometry
        this.routeFeature= null; // 线-feature
        this.geoMarker=null; // 标记
        this.startMarker= null; // 开始标记
        this.endMarker= null; // 结束标记
        this.styles={
            route: new Style({
                stroke: new Stroke({
                    lineDash:[20,10,20,10],
                    width: 6,
                    color: [237, 212, 0, 0.8]
                })
            }),
            icon: new Style({
                // 默认icon样式
                image: new CircleStyle({
                    radius: 7,
                    fill: new Fill({ color: "red" }),
                    stroke: new Stroke({
                        color: "white",
                        width: 2
                    })
                })
            }),
            geoMarker: new Style({
                // 设置标记样式
                image: new Icon({
                    anchor: [0.5,1],  // 偏移位置
                    // rotation: 0, // 旋转
                    // size: [52, 26], // 图标大小
                    scale:0.6,
                    src: movePng
                })
            }),
            start: new Style({
                // 设置开始标记样式
                image: new Icon({
                    anchor: [0.5,0.5],
                    scale:0.8,
                    src: startPng
                })
            }),
            end: new Style({
                // 设置结束标记样式
                image: new Icon({
                    anchor: [0.5, 0.5],
                    scale:0.8,
                    src: endPng
                })
            })
        };
        this.zoomScale=12;
        this.vectorLayer= null; // 矢量图层
        this.center= [] // 中心点
    }

    /**
     * 参数还原
     */
    paramsReduction(){
        this.progress=0;  //进度
        this.animating=false;//动画是否开始
        this.speed=0;// 速度
        this.nowTime= null; // 当前时间
        this.textContent= "开始";
        this.routeCoords=[]; // 数组点集合
        this.routeLength=0; // 数组长度
        this.route=null; // 线
        this.routeFeature= null; // 画线
        this.geoMarker=null; // 标记
        this.startMarker= null; // 开始标记
        this.endMarker= null; // 结束标记
        this.zoomScale=12;
        this.vectorLayer= null; // 矢量图层
        this.center= [] // 中心点
    }

    // 初始化地图
    initParams(map:any,routelatlon:Array<Array<number>>,centerPoint:Array<number>,zoomScale:number) {
        this._map=map;
        this.zoomScale=zoomScale;
        this.center=centerPoint;
        map.getView().animate({center: centerPoint,duration:200},{zoom: zoomScale,duration:200});
        this.routeCoords = routelatlon;
        this.routeLength = this.routeCoords.length;
        this.route = new LineString(this.routeCoords);

        this.routeFeature = new Feature({
            type: "route",
            geometry: this.route
        });
        this.geoMarker = new Feature({
            type: "geoMarker",
            geometry: new Point(this.routeCoords[0]),
        });
        this.startMarker = new Feature({
            type: "start",
            geometry: new Point(this.routeCoords[0])
        });
        this.endMarker = new Feature({
            type: "end",
            geometry: new Point(this.routeCoords[this.routeLength - 1])
        });
        let that=this;
        this.vectorLayer = new VectorLayer({
            source: new VectorSource({
                features: [
                    this.routeFeature,
                    this.geoMarker,
                    this.startMarker,
                    this.endMarker
                ]
                // 线、标记、开始标记、结束标记
            }),
            style: function(feature) {
                // 如果动画处于活动状态，则隐藏标记
                if (!that.animating && feature.get("type") === "geoMarker") {
                    return null;
                }
                return that.styles[feature.get("type")];
            },
            zIndex:9999
        });
        map.addLayer(that.vectorLayer)
        this.start();
        self=this;
    }






    // 运动轨迹开关
    handlerPlay() {
        if (this.textContent === "暂停") {
            this.stop(false);
        } else {
            this.start();
        }
    }

    // 轨迹移动
    moveFeature(event:any) {
        let vectorContext = getVectorContext(event);
        let frameState = event.frameState;
        if (self.animating) {
            let elapsedTime = frameState.time - self.nowTime;
            let index = Math.round((self.speed * elapsedTime) / 1000);
            // 进度条
            this.progress = Math.floor(
                ((100 / self.routeLength) * (self.speed * elapsedTime)) / 1000
            );
            if(index >= self.routeLength){
                index=index%self.routeLength
            }
            let currentPoint = new Point(self.routeCoords[index]);
            let feature = new Feature(currentPoint);
            vectorContext.drawFeature(feature, self.styles.geoMarker);
        }
        self._map.render(); // 开始移动动画
    }
    // 开始动画
    start() {
        if (this.animating) {
            this.stop(false);
        } else {
            this.animating = true;
            this.textContent = "暂停";
            this.nowTime = new Date().getTime();
            this.speed =10;
            this.geoMarker.setStyle(null); // hide geoMarker 隐藏标记
            this.vectorLayer.on("postrender", this.moveFeature);
            this._map.render();
        }
    }

    // 停止
    stop(ended:boolean) {
        this.progress = 0;
        this.animating = false;
        this.textContent = "开始";
        if( !this.routeCoords){return;}
        if(   this.routeCoords.length===0){
            return;
        }
        let coord = ended
            ? this.routeCoords[this.routeLength - 1]
            : this.routeCoords[0];
         this.geoMarker.getGeometry().setCoordinates(coord);
        //remove listener
        this.vectorLayer.un("postrender", this.moveFeature); // 删除侦听器
    }


    /**
     * 移除临时图层
     */
    removeLayer(){
        this.progress =100;
        this.stop(true);
        if(this.vectorLayer){
            this.vectorLayer.getSource().clear();
            this._map.removeLayer(this.vectorLayer)
        }
    }
}
export default  new PathNavigation();

`
const content3=`
import pathPoint from '../data/pathPoint.json'
import 'ol/ol.css'
import {Map, View} from 'ol'
import {register} from 'ol/proj/proj4'
import {WebGLTile} from 'ol/layer'
import {Style} from 'ol/style'
import {ImageTile, XYZ} from 'ol/source'
import proj4 from 'proj4'
import pathRoam from "@/widgets/Openlayer@10_3_1/js/pathRoam";


const runPathRoam = (map: any) => {
  //通过天地图，高德，EGIS拿到的数据一般都是字符串坐标,需要格式化处理
  let routeCoords =pathPoint;
  let centerPoint =pathPoint[Math.floor( pathPoint.length/2)];
  let zoomScale = 12;
  pathRoam.removeLayer();
  pathRoam.initParams(map, routeCoords, centerPoint, zoomScale)
}

const createMap = () => {
  proj4.defs('EPSG:4490', 'GEOGCS["China Geodetic Coordinate System 2000",DATUM["China_2000",SPHEROID["CGCS2000",6378137,298.257222101,AUTHORITY["EPSG","1024"]],AUTHORITY["EPSG","1043"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4490"]]')
  register(proj4)
  let layer = new WebGLTile({
    source: new ImageTile({
      attributions:
          'Tiles © <a href="https://services.arcgisonline.com/ArcGIS/' +
          'rest/services/World_Topo_Map/MapServer">ArcGIS</a>',
      url:
          'https://server.arcgisonline.com/ArcGIS/rest/services/' +
          'World_Topo_Map/MapServer/tile/{z}/{y}/{x}',
    }),
  })

  let map = new Map({
    target: 'map_content_1',
    layers: [layer],
    view: new View({
      center: [116.391478, 39.903185],
      projection: 'EPSG:4490',
      zoom: 5,
      maxZoom: 20,
      minZoom: 1
    }),
    overlays: [],
  })
  map.on('click', function (e) {

  })
  map.on('singleclick', function (e) {

  })
  runPathRoam(map);
}
`;
const createMap = () => {
  proj4.defs('EPSG:4490', 'GEOGCS["China Geodetic Coordinate System 2000",DATUM["China_2000",SPHEROID["CGCS2000",6378137,298.257222101,AUTHORITY["EPSG","1024"]],AUTHORITY["EPSG","1043"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4490"]]')
  register(proj4)
  let layer = new WebGLTile({
    source: new ImageTile({
      attributions:
          'Tiles © <a href="https://services.arcgisonline.com/ArcGIS/' +
          'rest/services/World_Topo_Map/MapServer">ArcGIS</a>',
      url:
          'https://server.arcgisonline.com/ArcGIS/rest/services/' +
          'World_Topo_Map/MapServer/tile/{z}/{y}/{x}',
    }),
  })

  let map = new Map({
    target: 'map_content_1',
    layers: [layer],
    view: new View({
      center: [116.391478, 39.903185],
      projection: 'EPSG:4490',
      zoom: 5,
      maxZoom: 20,
      minZoom: 1
    }),
    overlays: [],
  })
  map.on('click', function (e) {

  })
  map.on('singleclick', function (e) {

  })
  runPathRoam(map);
}

const runPathRoam = (map: any) => {
  //通过天地图，高德，EGIS拿到的数据一般都是字符串坐标,需要格式化处理
  let routeCoords =pathPoint;
  let centerPoint =pathPoint[Math.floor( pathPoint.length/2)];
  let zoomScale = 12;
  pathRoam.removeLayer();
  pathRoam.initParams(map, routeCoords, centerPoint, zoomScale)
}

onMounted(() => {
  nextTick(() => {
    Prism.highlightAll();
    createMap();
  })

})
</script>

<style lang="scss" scoped>
/* 引入Prism.js的CSS主题 */
@import 'prismjs/themes/prism-tomorrow.css';
@import '../css/openlayer_common.css';

.create_open_path_roam_box {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: row-reverse;
  background-color: rgba(44, 62, 80, 0.5);

  .inner_content_box {
    width: calc(100% - 300px - 100px - 500px);
    height: calc(100% - 20px);
    margin-top: 10px;
    margin-right: 350px;
    overflow-x: hidden;
    overflow-y: auto;
    background-color: rgba(255, 255, 255, 0.8);
  }

}
</style>
